import { getInfoAPI, homeAPI, loginAPI, noticeAPI } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {},
  routes: [],
  userData: {},
  noticeData: []
}

const mutations = {
  saveToken(state, token) {
    state.token = token
  },
  saveInfo(state, data) {
    state.userInfo = data
  },
  saveRoutes(state, router) {
    // 保存该用户有权限去的路由页面
    state.routes = router
  },
  saveHome(state, data) {
    state.userData = data
  },
  saveNotice(state, data) {
    state.noticeData = data
  }
}

const actions = {
  async toLogin(comtext, data) {
    // 调用登录接口
    const res = await loginAPI(data)
    // 把token存进本地存储
    setToken(res.data.data)
    // 调用mutations 里面函数
    comtext.commit('saveToken', res.data.data)
    // 路由之间进行跳转
    router.push('/')
    Message.success('登录成功')
  },
  async getInfoAction(context) {
    // 调用首页信息接口
    const res = await getInfoAPI()
    context.commit('saveInfo', res.data.data)
  },
  async homeAction(context) {
    const res = await homeAPI()
    context.commit('saveHome', res.data.data)
  },
  async noticeAction(context) {
    const res = await noticeAPI()
    context.commit('saveNotice', res.data.data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

